import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:palmf_hid/common/entities/data_base/my_database.dart';
import 'package:palmf_hid/common/services/Db.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/common/values/my_color.dart';
import 'package:palmf_hid/common/widgets/empty_widget.dart';
import 'package:palmf_hid/pages/main/widget/history_item.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'check_logic.dart';
import 'check_state.dart';

class CheckPage extends StatefulWidget {
  const CheckPage({Key? key}) : super(key: key);

  @override
  State<CheckPage> createState() => _CheckPageState();
}

class _CheckPageState extends State<CheckPage>
    with AutomaticKeepAliveClientMixin {
  final CheckLogic logic = Get.put(CheckLogic());
  final CheckState state = Get.find<CheckLogic>().state;

  @override
  bool get wantKeepAlive => true; // 是否需要缓存
  @override
  Widget build(BuildContext context) {
    return _buildBody();
  }

  _buildBody() {
    return Obx(() => Container(
          width: 1.sw,
          height: 1.sh,
          child: Column(
            children: [
              SizedBox(
                height: 40,
                child: _buildOperate(),
              ),
              Expanded(child: _buildList()),
            ],
          ),
          color: MyColor.c_FFFFFFFF,
        ));
  }

  _buildOperate() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        InkWell(
          child: Text("同步"),
          onTap: () {
            logic.handleSyncAllDevice();
          },
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          child: Text("清除二维码"),
          onTap: () {
            logic.handleSendClearQrCodeOrder();
          },
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          child: Text("删除手持机所有数据"),
          onTap: () {
            logic.handleDeleteDeviceTestData();
          },
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          child: Text("刷新列表"),
          onTap: () {
            logic.refreshController.requestRefresh();
          },
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          child: Text("删除本地数据"),
          onTap: () {
            logic.handleDeleteDb();
          },
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          child: Text("获取时间"),
          onTap: () {
            logic.handleGetDeviceTimeData();
          },
        ),
        SizedBox(
          width: 10,
        ),
        InkWell(
          child: Text("设置时间"),
          onTap: () {
            logic.handleSetDeviceTimeData();
          },
        ),SizedBox(
          width: 10,
        ),
      ],
    );
  }

  _buildList() {
    return Container(
        padding: const EdgeInsets.only(right: 10, top: 5, bottom: 5),
        child: SmartRefresher(
          key: logic.refresherKey,
          controller: logic.refreshController,
          enablePullUp: false,
          enablePullDown: true,
          onRefresh: logic.onRefresh,
          child: state.historyResultList.isEmpty
              ? Center(
                  child: emptyWidget(notice: state.dataState),
                )
              : ListView.separated(
                  separatorBuilder: (_, index) => const Divider(
                        height: 10,
                        thickness: 1,
                      ),
                  itemBuilder: (context, index) => InkWell(
                        onTap: () {
                          logic.handleSelect(index);
                        },
                        child: Row(
                          children: [
                            Checkbox(
                              fillColor:WidgetStateProperty.resolveWith((Set<WidgetState> states) {
                                const Set<WidgetState> interactiveStates = <WidgetState>{
                                  WidgetState.pressed,
                                  WidgetState.hovered,
                                  WidgetState.focused,
                                };
                                if (states.contains(WidgetState.disabled)) {
                                  return ThemeData.from(colorScheme: ColorScheme.light()).disabledColor;
                                }
                                if (states.contains(WidgetState.selected)) {
                                  return Colors.white;
                                }
                                if (states.any(interactiveStates.contains)) {
                                  return Colors.red;
                                }
                                // 最终返回
                                return Colors.white;
                              }),
                              checkColor: MyColor.account_color,
                              activeColor: MyColor.c_99000000,
                              value: state.historyResultList[index].selected,
                              onChanged: (bool? value) {
                                logic.handleSelect(index);
                              },
                            ),
                            Expanded(
                                child: historyItem(
                                    hideOperate: true,
                                    index: index,
                                    result:
                                        state.historyResultList[index].results!,
                                    onDelete: (Results result) {
                                      DbService.to
                                          .deleteHistoryRecordById(result.id)
                                          .then((value) async {
                                        if (value > 0) {
                                          state.historyResultList
                                              .removeAt(index);
                                          if (state.historyResultList.length <
                                              10) {
                                            logic.refreshController
                                                .requestRefresh();
                                          }

                                          var temp = await DbService.to
                                              .allResultDataCountByDeviceNoOrProject(
                                                  state.deviceNo,
                                                  state.project,
                                                  state.checkTime);

                                          state.total = temp.length;
                                        } else {
                                          MyToastUtil.show("fail".tr);
                                        }
                                      });
                                    },
                                    onWifiPrint: (Results result) {},
                                    onPrint: (Results result) async {})),
                          ],
                        ),
                      ),
                  itemCount: state.historyResultList.length),
        ));
  }

  @override
  void dispose() {
    Get.delete<CheckLogic>();
    super.dispose();
  }
}
